package com.drojian.demo4.internet;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.drojian.demo.R;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpActivity extends AppCompatActivity implements View.OnClickListener {
    private Button send;
    private TextView responseText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part4_activity_ok_http);
        send = findViewById(R.id.sendRequestBtn);
        responseText = findViewById(R.id.responseText);
        send.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.sendRequestBtn:
                senRequest();
                break;
        }
    }

    private void senRequest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://www.jingdong.com")
                            .build();
                    Response response = client.newCall(request).execute();
                    String string = response.body().toString();
                    showResponse(string);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


            }
        }).start();
    }

    private void showResponse(String string) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(string);
            }
        });
    }
}